#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版Anki卡片生成工具
纯Python实现，无需额外依赖
"""

import os
import sys

def generate_sample_template():
    """生成示例模板"""
    sample = """光纤通道(FC)为何更适合金融高频交易场景？
存储协议
---
✅ 微秒级延迟要求+零丢包保障
📚 光纤协议栈比TCP/IP精简，省略了重传和拥塞控制机制，直接映射到物理层
❗ FC像F1赛车（专用赛道/极简设计），IP像货车（通用公路/频繁检修）
⛔️ 曾将网络带宽视为低延迟首要因素，忽略了协议开销的影响
🔍 延迟敏感型系统需要绕过传统协议栈的冗余机制
===============
IP SAN和FC SAN的主要区别是什么？
存储协议
---
✅ 传输协议不同：FC使用光纤通道协议，IP SAN使用TCP/IP协议
📚 FC SAN专为存储设计，提供predictable性能；IP SAN基于现有IP网络，成本更低但性能有波动
❗ FC像专用高速公路，IP SAN像普通公路共享车流
⛔️ 曾认为两者只是速度差异，忽略了协议可靠性的根本区别
🔍 选择取决于对性能可预测性和成本的不同权衡
==============="""
    return sample

def parse_custom_format(content):
    """解析自定义格式并移除emoji"""
    import re
    cards = []
    card_blocks = content.split("===============")
    
    # emoji表情正则表达式
    emoji_pattern = re.compile(
        "["
        "\U0001F600-\U0001F64F"  # emoticons
        "\U0001F300-\U0001F5FF"  # symbols & pictographs
        "\U0001F680-\U0001F6FF"  # transport & map symbols
        "\U0001F1E0-\U0001F1FF"  # flags
        "\U00002702-\U000027B0"  # dingbats
        "\U000024C2-\U0001F251" 
        "\U0001F900-\U0001F9FF"  # supplemental symbols
        "\u2600-\u26FF\u2700-\u27BF"  # other symbols
        "]+", flags=re.UNICODE)
    
    for block in card_blocks:
        block = block.strip()
        if not block:
            continue
            
        if "---" not in block:
            continue
            
        front, back = block.split("---", 1)
        front_lines = [line.strip() for line in front.strip().split('\n') if line.strip()]
        back_lines = [line.strip() for line in back.strip().split('\n') if line.strip()]
        
        if len(front_lines) < 1:
            continue
            
        card = {
            'question': emoji_pattern.sub('', front_lines[0]).strip() if front_lines else '',
            'category': emoji_pattern.sub('', front_lines[1]).strip() if len(front_lines) > 1 else '未分类',
            'core_answer': '',
            'full_explanation': '',
            'memory_tip': '',
            'common_mistake': '',
            'essential_understanding': ''
        }
        
        # 解析背面内容
        for line in back_lines:
            clean_line = emoji_pattern.sub('', line).strip()
            if line.startswith('✅'):
                card['core_answer'] = clean_line[1:].strip()
            elif line.startswith('📚'):
                card['full_explanation'] = clean_line[1:].strip()
            elif line.startswith('❗'):
                card['memory_tip'] = clean_line[1:].strip()
            elif line.startswith('⛔️'):
                card['common_mistake'] = clean_line[1:].strip()
            elif line.startswith('🔍'):
                card['essential_understanding'] = clean_line[1:].strip()
        
        cards.append(card)
    
    return cards

def format_for_anki(cards):
    """格式化为Anki可导入的制表符分隔格式"""
    lines = []
    
    # 添加标题行
    lines.append("问题\t知识点分类\t核心答案\t完整解析\t记忆技巧\t我的误区\t本质理解")
    
    for card in cards:
        # 转义制表符和换行符
        question = str(card['question']).replace('\t', ' ').replace('\n', ' ')
        category = str(card['category']).replace('\t', ' ').replace('\n', ' ')
        core_answer = str(card['core_answer']).replace('\t', ' ').replace('\n', ' ')
        full_explanation = str(card['full_explanation']).replace('\t', ' ').replace('\n', ' ')
        memory_tip = str(card['memory_tip']).replace('\t', ' ').replace('\n', ' ')
        common_mistake = str(card['common_mistake']).replace('\t', ' ').replace('\n', ' ')
        essential_understanding = str(card['essential_understanding']).replace('\t', ' ').replace('\n', ' ')
        
        line = f"{question}\t{category}\t{core_answer}\t{full_explanation}\t{memory_tip}\t{common_mistake}\t{essential_understanding}"
        lines.append(line)
    
    return '\n'.join(lines)

def convert_file(input_file, output_file):
    """转换文件"""
    try:
        # 尝试多种编码读取
        content = None
        for encoding in ['utf-8', 'utf-8-sig', 'gb2312', 'gbk', 'gb18030']:
            try:
                with open(input_file, 'r', encoding=encoding) as f:
                    content = f.read()
                break
            except UnicodeDecodeError:
                continue
        
        if content is None:
            print("无法识别文件编码，请确保文件为UTF-8或GBK编码")
            return False
        
        cards = parse_custom_format(content)
        anki_content = format_for_anki(cards)
        
        # 使用UTF-8 with BOM确保兼容性
        with open(output_file, 'w', encoding='utf-8-sig') as f:
            f.write(anki_content)
        
        print(f"成功转换 {len(cards)} 张卡片到 {output_file}")
        return True
    except Exception as e:
        print(f"转换失败: {e}")
        return False

def main():
    """主函数"""
    print("Anki卡片生成工具")
    print("=" * 30)
    
    if len(sys.argv) > 1 and sys.argv[1] == "--sample":
        sample = generate_sample_template()
        with open("sample_template.txt", "w", encoding="utf-8") as f:
            f.write(sample)
        print("示例模板已生成: sample_template.txt")
        return
    
    if len(sys.argv) == 3:
        input_file = sys.argv[1]
        output_file = sys.argv[2]
    else:
        print("使用方法:")
        print("1. 生成示例模板: python anki_card_generator_simple.py --sample")
        print("2. 转换文件: python anki_card_generator_simple.py input.txt output.txt")
        print("\n或者拖拽文件到批处理脚本")
        return
    
    if not os.path.exists(input_file):
        print(f"输入文件不存在: {input_file}")
        return
    
    convert_file(input_file, output_file)

if __name__ == "__main__":
    main()